package com.xci.platform.helper;

import cn.hutool.core.util.StrUtil;
import com.xci.platform.core.BoolMessage;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;

public class WebHelper {
    /**
     * 判断文件是否是图片类型
     */
    public static boolean isImage(InputStream imageFile) {
        try {
            Image img = ImageIO.read(imageFile);
            return img != null && img.getWidth(null) > 0 && img.getHeight(null) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断请求是否为ajax请求
     */
    public static boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }

    /**
     * 判断请求是否为app请求
     */
    public static boolean isApp(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "AppHttpRequest".equals(request.getHeader("X-Requested-With")));
    }

    /**
     * 输出Json对象
     *
     * @param data     输出的Json对象
     * @param response 响应对象
     * @throws IOException IO异常
     */
    public static void echoJson(BoolMessage data, HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.getWriter().write(JsonHelper.serialize(data));
    }

    /**
     * 获取浏览器信息
     */
    public static String getBrowserInfo(HttpServletRequest request){
        if (request.getHeader("User-Agent") != null) {
            UserAgent agent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
            return StrUtil.format("{} {} {}"
                    , agent.getOperatingSystem().getName()
                    , agent.getBrowser().getName()
                    , agent.getBrowserVersion().getMajorVersion());
        }
        return "";
    }

    /**
     * 获取站点Url信息
     */
    public static String getSiteUrl() {
        ServletRequestAttributes servlet = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servlet != null) {
            HttpServletRequest request = servlet.getRequest();
            String scheme = request.getScheme();//http
            String serverName = request.getServerName();//localhost
            int serverPort = request.getServerPort();//8080
            return StringHelper.format("{}://{}:{}", scheme, serverName, serverPort);
        }
        return "";
    }
}
